#include "groupchatdialog.h"
#include "qqmlcontext.h"
#include "ui_groupchatdialog.h"
#include"global.h"
#include "usermgr.h"
#include"widget/chatuserwid.h"
#include "../tcpmgr.h"

/*
 * 用uuid表示唯一的群聊号
 * 创建群聊时需要指定头像
*/

GroupChatDialog::GroupChatDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::GroupChatDialog)
{
    ui->setupUi(this);
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tableWidget->horizontalHeader()->setVisible(false);
    ui->tableWidget->verticalHeader()->setVisible(false);

    QNetworkAccessManager *net = new QNetworkAccessManager(this);
    connect(net, &QNetworkAccessManager::finished, this, &GroupChatDialog::slot_add_friend_list);
    QNetworkRequest request(GATE_URL+"/friendList");
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    QJsonObject json_obj;
    json_obj["uid"] = UserMgr::GetInstance()->getUid();
    net->post(request, QJsonDocument(json_obj).toJson());
}

GroupChatDialog::~GroupChatDialog()
{
    delete ui;
}

void GroupChatDialog::slot_add_friend_list(QNetworkReply *reply)
{
    QJsonParseError jsonError;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(reply->readAll(), &jsonError);
    if (jsonError.error != QJsonParseError::NoError){
        qDebug() << "JSON解析错误：" << jsonError.errorString();
    }
    QJsonObject jsonObj = jsonDoc.object();

    int error = jsonObj["error"].toInt();
    if(static_cast<ErrorCodes>(error) != ErrorCodes::SUCCESS){
        return;
    }
    // 处理 friends
    QJsonArray friendsArray = jsonObj["friends"].toArray();
    for (const QJsonValue &value : friendsArray){
        QJsonObject friendObject = value.toObject();
        QString name = friendObject["user"].toString();
        isGetAvatar(name);
        qDebug() << name;
        ChatUserWid *customWidget{new ChatUserWid(name)};
        connect(customWidget, &ChatUserWid::sig_switch_user, this, &GroupChatDialog::slot_add_friend);
        customWidget->closeRedDot();
        customWidget->setContactsStyle();
        QListWidgetItem *item{new QListWidgetItem(ui->listWidget)};
        ui->listWidget->setItemWidget(item, customWidget);
        item->setSizeHint(customWidget->sizeHint());
        ui->listWidget->insertItem(_userNum++, item);
    }
}

void GroupChatDialog::slot_add_friend(const QString& name)
{
    if (_group.contains(name)) return;

    int num = _groupNum++ % 3;
    if (num == 0){
        int rowCount = ui->tableWidget->rowCount(); // 获取当前行数
        ui->tableWidget->insertRow(rowCount); // 在末尾添加一行
        ui->tableWidget->setRowHeight(rowCount, ui->tableWidget->columnWidth(0));
    }
    int rowCount = ui->tableWidget->rowCount(); // 获取当前行数
    _group.append(name);

    // 创建QLabel
    QLabel *label = new QLabel(ui->tableWidget);
    label->setScaledContents(true);
    label->setPixmap(QPixmap(AvatarPath.arg(name)));
    ui->tableWidget->setCellWidget(rowCount - 1, num, label); // 将label添加到新行的第一个单元格
}

void GroupChatDialog::on_pushButton_2_clicked()
{
    close();
}

void GroupChatDialog::on_pushButton_clicked()
{
    QString name = ui->lineEdit->text();
    if (ui->label_2->pixmap().isNull() || name.isEmpty()){
        QMessageBox::information(NULL, "提示", "请选择头像和填写群名", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
        return;
    }
    QUuid id = QUuid::createUuid();
    QString uuid = id.toString();
    qDebug() << uuid;

    QImage croppedPixmap(TemporaryAvatar);
    QByteArray byteArray;
    QBuffer buffer(&byteArray);
    buffer.open(QIODevice::WriteOnly);
    croppedPixmap.save(&buffer, "JPG");  // 可以选择其他格式如"JPG"
    croppedPixmap.save(AvatarPath.arg(name));

    QJsonObject json_obj;
    json_obj["token"] = UserMgr::GetInstance()->getToken();
    json_obj["group_uuid"] = uuid;
    json_obj["group_name"] = name;
    QJsonArray json_array;
    json_array.append(UserMgr::GetInstance()->getName());
    for (const QString& name : _group){
        json_array.append(name);
    }
    json_obj["group_member"] = json_array;
    json_obj["avatar"] = QJsonValue::fromVariant(byteArray.toBase64());

    QJsonDocument doc(json_obj);
    emit TcpMgr::GetInstance()->sig_send_data(ReqId::ID_CREATE_GROUP_CHAT, doc.toJson(QJsonDocument::Compact));
    emit sig_create_group(name, _group.count(), uuid);
}

void GroupChatDialog::on_pushButton_3_clicked()
{
    if (engine != nullptr){
        qDebug() << "engine";
        return;
    }

    engine = new QQmlApplicationEngine(this);
    //对qml暴露tailor
    tailor = new Tailor;
    connect(tailor, &Tailor::sig_head_portrait_finish, this,[this](){
        QPixmap ico(TemporaryAvatar);
        ui->label_2->setPixmap(ico);
    });
    connect(tailor, &Tailor::qmlClose, this, [this]{
        engine->deleteLater();
        tailor->deleteLater();
        tailor = nullptr;
        engine = nullptr;
    });
    engine->rootContext()->setContextProperty("tailor", tailor);
    engine->load(QUrl(QStringLiteral("qrc:/test/qrc/Main.qml")));
}

void GroupChatDialog::on_emptyBtn_clicked()
{
    ui->tableWidget->clear();
    ui->tableWidget->setRowCount(0);
    _group.clear();
    _groupNum = 0;
}

